﻿using IdentityModel;
using IdentityServer.Models;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using System.Security.Claims;

namespace IdentityServer.Extensions
{
    //自定义验证
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly IdentityServerContext _dbContext;

        public ResourceOwnerPasswordValidator(IdentityServerContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 验证用户名密码
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var passWord = context.Password;
            var userName = context.UserName;
            var user = _dbContext.Users.Where(u => u.UserCode.Equals(userName) && u.Password.Equals(passWord)).FirstOrDefault();
            if (null == user)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid credential");
            }
            else
            {
                var claims = new List<Claim>()
                {
                    new("userId", $"{user.Id}"),
                    new("userCode", $"{user.UserCode}")
                };

                context.Result = new GrantValidationResult(
                    subject: user.Id.ToString(),
                    authenticationMethod: OidcConstants.AuthenticationMethods.Password,
                    claims.ToArray()
                );
            }
            return Task.FromResult(0);
        }
    }
}
